<?php

namespace Tbf\Bundle\AjkApiBundle;

use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Translation\TranslatorInterface;
use Tbf\Bundle\AjkApiBundle\Annotation\Api;
use Tbf\Bundle\SerializerBundle\Serializer;

class AjkApiHandler
{
    protected $reader;
    protected $serializer;
    public function __construct(Serializer $serializer=null,TranslatorInterface $translator=null)
    {
        $this->serializer = $serializer;
        $this->translater = $translator;
    }
    public function outputToResponse($output,Api $api_config = null)
    {
        if ($this->translater!==null) {
            //lazy load translator
            if ($output[1]===null) {
                $err_local = '';
            } else {
                $err_local = $this->translater->trans($output[1]);
            }
        } else {
            $err_local = $output[1];
        }
        if ($api_config===null){
            $group = null;
        }else{
            $group = $api_config->group;
        }
        //lazy load tbf_serializer
        if ($output[0]===null) {
            $data = $output[0];
        } else {
            $data = $this->toArray($output[0],$group);
        }
        $resp = new Response(json_encode(array(
            'data'=>$data,
            'err'=>$output[1],
            'err_local'=>$err_local
        )));
        //在access denied的时候 http code会被搞到 异常的code(403)上面去!!!
        // 这个地方一定是200
        $resp->headers->set('X-Status-Code',200);

        return $resp;
    }
    protected function toArray($obj,$group){
        if ($this->serializer!==null){
            return $this->serializer->toArray($obj,$group);
        }
        return $obj;
    }
    public function inputFromRequest(Request $request,Api $api_config = null)
    {
        if ($api_config===null){
            $api_config = new Api();
        }
        if ($api_config->allow_json &&
            $request->getContentType()==='json') {
            return json_decode($request->getContent(),true);
        }
        if ($api_config->input_method===Api::INPUT_POST){
            return $request->request->all();
        }
        if ($api_config->input_method===Api::INPUT_GET){
            return $request->query->all();
        }
        if ($api_config->input_method===Api::INPUT_POST_GET ||
            $api_config->input_method===Api::INPUT_ALL
        ){
            return array_merge($request->request->all(),$request->query->all());
        }
    }
    public function isValidOutput($output)
    {
        if (!is_array($output)) {
            return false;
        }
        if (count($output)!==2) {
            return false;
        }
        if ( !(is_null($output[1])||is_string($output[1])) ) {
            return false;
        }

        return true;
    }
}
